package com.meaningful.thinking.aqs_demo;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        int[] count = new int[]{1000};
        List<Thread> threads = new ArrayList<>();

        MyLock lock = new MyLock();
        for (int i = 0; i < 5; i++) {
            threads.add(
                    new Thread(() -> {
                        for (int j = 0; j < 5; j++) {
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            lock.lock();
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            count[0]--;
                        }
                        for (int j = 0; j < 5; j++) {
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            lock.unlock();
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    })
            );
        }

        for (Thread thread : threads) {
            thread.start();
        }

        // 主线程等待所有的线程运行结束
        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println(count[0]);
    }

}
